package com.ruoyi.client.controller;


import com.ruoyi.client.domain.vo.request.ClientRewardExchangeRequestVo;
import com.ruoyi.client.service.IRewardService;
import com.ruoyi.client.service.IUserShippingAddressService;
import com.ruoyi.client.util.ResponseResult;
import com.ruoyi.common.core.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 奖品管理Controller
 * 
 * @author ruoyi
 * @date 2024-11-21
 */
@RestController
@RequestMapping("/client/reward")
public class ClientRewardController extends BaseController {
    @Autowired
    private IRewardService rewardService;
    
    @Autowired
    private IUserShippingAddressService addressService;

    /**
     * 查询奖品功能首页
     */
    @GetMapping("/index")
    public ResponseResult getRewardIndex(@RequestParam("userId") String userId) {
        return ResponseResult.success(rewardService.getRewardIndex(userId));
    }

    /**
     * 获取奖品详情
    * */
    @GetMapping("{id}")
    public ResponseResult getRewardDetail(@PathVariable("id") Integer id) {
        return ResponseResult.success(rewardService.getRewardDetail(id));
    }
    /**
     * 兑换奖品
     */
    @PostMapping("/exchange")
    public ResponseResult exchangeReward(@RequestBody ClientRewardExchangeRequestVo requestVo) {
        // 参数校验
        if (requestVo.getReceiveType() == null) {
            return ResponseResult.fail("请选择领取方式");
        }
        
        // 如果选择邮寄，验证收货地址
        if (requestVo.getReceiveType() == 2) {
            if (requestVo.getAddressId() == null) {
                return ResponseResult.fail("请选择收货地址");
            }
            
            // 验证地址是否存在且属于该用户
            if (addressService.getUserAddressById(requestVo.getAddressId()) == null) {
                return ResponseResult.fail("收货地址不存在");
            }
        }
        
        int i = rewardService.exchangeReward(requestVo);
        if(i==-1){
            return ResponseResult.fail("积分不足");
        }else if(i==-2){
            return ResponseResult.fail("奖品库存不足");
        }else if(i==-3){
            return ResponseResult.fail("收货地址不存在");
        }else {
            return ResponseResult.success("兑换成功");
        }
    }

    /**
     * 获取用户积分记录
     */
    @GetMapping("/creditRecord")
    public ResponseResult getCreditRecord(@RequestParam("userId") String userId) {
        return ResponseResult.success(rewardService.getCreditRecord(userId));
    }
}
